﻿using Entity;
using Microsoft.AspNetCore.Http;
using ServiceCore;
using ServiceCore.Tool.Dapper;
using ServiceCore.Tool.ES;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using static ServiceCore.Tool.ES.Es_knowledge;

namespace Customer.Bussiness_Service
{


    public interface Iknowledge_service
    {
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="parent_id"></param>
        /// <returns></returns>
        ResultObjModel get_list(string parent_id = "top");
        /// <summary>
        /// 获取知识库类型数据
        /// </summary>
        /// <returns></returns>
        ResultObjModel get_alllist(string top_id = "");
        /// <summary>
        /// 保存知识库类型数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        ResultModel save_item(knowledge_type model);
        /// <summary>
        /// 删除知识库类型
        /// </summary>
        /// <param name="type_id"></param>
        /// <returns></returns>
        ResultModel del_item(string type_id);
        /// <summary>
        /// 变更位置
        /// </summary>
        /// <param name="change_type"></param>
        /// <param name="type_id"></param>
        /// <returns></returns>
        ResultModel change_position(string change_type, string type_id);
        /// <summary>
        /// 保存知识库文章
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultObjModel save_knowledge(knowledge_base Params);
        /// <summary>
        /// 查询搜索
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultObjModel knowledge_search(knowledge_search query);
        /// <summary>
        /// 查询已发布的知识库文章
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultObjModel knowledge_search_to_public(knowledge_search query);
        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        ResultObjModel get_knowledge(string id);
        /// <summary>
        /// 变更知识库状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        ResultObjModel change_knowledge_state(string id, int? state, DateTime? showtime = null);
        /// <summary>
        /// 删除知识库
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        ResultObjModel del_knowledge(string id);
        /// <summary>
        /// 开始分享
        /// </summary>
        /// <param name="id"></param>
        /// <param name="is_long"></param>
        /// <param name="set_params"></param>
        /// <returns></returns>
        ResultObjModel start_share(string id, bool? is_long, share_params? set_params);
        /// <summary>
        /// 分享页获取分享信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        ResultObjModel get_knowledge_for_share(string id);
        /// <summary>
        /// 取消分享
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        ResultObjModel cancel_share(string id); 
        /// <summary>
        /// 获取看板数据
        /// </summary>
        /// <param name="role_id"></param>
        /// <returns></returns>
        ResultObjModel get_kanban_index(string type_id);
        /// <summary>
        /// 标记文章已读
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        ResultObjModel read_knowledge(string uid, string id);
        /// <summary>
        /// 获取看板列表数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultObjModel get_kanban_pagelist(knowledge_search query);
        /// <summary>
        /// 关键字搜索
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultObjModel search_kanben_pagelist(knowledge_search query);
    }
    public class knowledge_service : Iknowledge_service
    {
        private readonly IToole_DI _tool;
        private readonly IEs_knowledge _es_service;
        private readonly IHttpContextAccessor _context;
        private static List<knowledge_type> knowledge_list = null;
        private List<knowledge_type> getknowledge_list
        {
            get
            {
                if (knowledge_list == null)
                {
                    List<knowledge_type> db_list = _tool.di_db.GetList<knowledge_type>("select * from knowledge_type", null).ToList();
                    knowledge_list = db_list;
                }
                return knowledge_list;
            }
        }
        private void refknowledge_list()
        {
            Task.Factory.StartNew(() =>
            {
                List<knowledge_type> db_list = _tool.di_db.GetList<knowledge_type>("select * from knowledge_type", null).ToList();
                knowledge_list = db_list;
            });
        }

        public knowledge_service(IToole_DI Tool, IEs_knowledge EsService, IHttpContextAccessor Context)
        {
            _tool = Tool;
            _es_service = EsService;
            _context = Context;
        }

        #region 知识库类型 

        /// <summary>
        /// 获取知识库数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultObjModel get_list(string parent_id = "top")
        {
            return CoreStartDo.ResultAction(result =>
            {
                List<knowledge_type> list = getknowledge_list.Where(s => s.parent_id == parent_id).OrderBy(s => s.sort).ToList();
                result.code = 0;
                result.msg = "success";
                result.data = from o in list
                              select new
                              {
                                  o.type_id,
                                  o.parent_id,
                                  o.type_name
                              };
                return result;
            });
        }

        /// <summary>
        /// 获取知识库数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultObjModel get_alllist(string top_id = "")
        {
            return CoreStartDo.ResultAction(result =>
            {
                List<knowledge_type_forsearch> search_result = new List<knowledge_type_forsearch>();
                var db_list = getknowledge_list;
                List<string> ids = new List<string>();
                foreach (var item in db_list.Where(s => s.parent_id == "top").OrderBy(s => s.sort))
                {
                    knowledge_type_forsearch new_item = new knowledge_type_forsearch()
                    {
                        type_id = item.type_id,
                        parent_id = item.parent_id,
                        type_name = item.type_name
                    };
                    new_item.kid_list = get_next(db_list, item.type_id, ref ids);
                    search_result.Add(new_item);
                }
                result.code = 0;
                result.msg = "success";
                result.data = search_result;
                if (!string.IsNullOrWhiteSpace(top_id))
                {
                    result.data = search_result.Where(s => s.type_id == top_id);
                }
                return result;
            });
        }
        private List<knowledge_type_forsearch> get_next(List<knowledge_type> db_list, string parentid, ref List<string> ids)
        {
            List<knowledge_type_forsearch> search_result = new List<knowledge_type_forsearch>();
            if (db_list.Where(s => s.parent_id == parentid).Any())
            {
                foreach (var item in db_list.Where(s => s.parent_id == parentid).OrderBy(s => s.sort))
                {
                    knowledge_type_forsearch new_item = new knowledge_type_forsearch()
                    {
                        type_id = item.type_id,
                        parent_id = item.parent_id,
                        type_name = item.type_name
                    };
                    new_item.kid_list = get_next(db_list, item.type_id, ref ids);
                    ids.Add(new_item.type_id);
                    search_result.Add(new_item);
                }
                return search_result;
            }
            else
            {
                return new List<knowledge_type_forsearch>();
            }
        }

        /// <summary>
        /// 保存知识库类型
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResultModel save_item(knowledge_type model)
        {
            ResultModel result = new ResultModel();
            try
            {
                #region  基础验证 
                if (string.IsNullOrWhiteSpace(model.type_name))
                {
                    result.code = 1;
                    result.msg = "类型名称不能为空";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(model.parent_id))
                {
                    model.parent_id = "top";
                }
                #endregion
                #region 数据处理 
                if (string.IsNullOrWhiteSpace(model.type_id))
                {
                    //添加
                    model.type_id = _tool.di_getid.IGet_SnowFlake_Id;
                    model.addtime = DateTime.Now;
                    model.adduser = _tool.di_user.USER.uid;
                    //获取同级别数量
                    int def_count = getknowledge_list.Where(s => s.parent_id == model.parent_id).Max(s => s.sort).HasValue ? getknowledge_list.Where(s => s.parent_id == model.parent_id).Max(s => s.sort).Value : 0;
                    model.sort = def_count + 1;
                    int addrows = _tool.di_db.Add(model);
                    if (addrows > 0)
                    {
                        result.code = 0;
                        result.msg = "添加成功";
                        refknowledge_list();
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "添加失败 DB error";
                    }
                }
                else
                {
                    //编辑
                    var needupdate = _tool.di_db.GetModel<knowledge_type>(new string[] { "type_id=@type_id" }, new { model.type_id });
                    if (needupdate == null)
                    {
                        result.code = 1;
                        result.msg = "修改信息不存在";
                        return result;
                    }
                    needupdate.type_name = model.type_name;
                    if (needupdate.parent_id != model.parent_id)
                    {
                        //变更所属上下级了 需要重新排序
                        needupdate.sort = getknowledge_list.Where(s => s.parent_id == model.parent_id).Max(s => s.sort);
                        if (needupdate.sort.HasValue)
                        {
                            needupdate.sort++;
                        }
                        else
                        {
                            needupdate.sort = 1;
                        }
                    }
                    needupdate.parent_id = model.parent_id;
                    int updaterows = _tool.di_db.Update<knowledge_type>(new string[] { "type_name", "parent_id", "sort" }, new string[] { "type_id=@type_id" }, needupdate);
                    if (updaterows > 0)
                    {
                        result.code = 0;
                        result.msg = "修改成功";
                        refknowledge_list();
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "修改成功 DB error";
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.msg = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 不能删除
        /// </summary>
        private static string[] can_not_del = new string[] { "sale_system", "richang_shijian", "huiyi_jilu", "hangye_xinwen", "gongzuo_liucheng", "zhidu_guifan", "jingpin_fenxi", "zhuanye_zhishi", "jixing_peizhi", "xiaoshou_jiqiao"
          ,"after_sale_system","work_system"
        };
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <returns></returns>
        public ResultModel del_item(string type_id)
        {
            return CoreStartDo.ResultAction(result =>
            { 
                if (can_not_del.Contains(type_id))
                {
                    result.code = 1;
                    result.msg = "无法删除系统关联项";
                    return result;
                }
                List<string> ids = new List<string>();
                List<knowledge_type_forsearch> need_dels = get_next(getknowledge_list, type_id, ref ids);
                ids.Add(type_id);
                var resultCount = _tool.di_db.do_Execute("delete from knowledge_type where type_id in @type_ids", new { type_ids = ids });
                if (resultCount > 0)
                {
                    result.code = 0;
                    result.msg = "删除成功";
                    refknowledge_list();
                }
                else
                {
                    result.code = 1;
                    result.msg = "删除失败,没有条目被改变";
                }
                return result;
            });
        }

        /// <summary>
        /// 更改位置
        /// </summary>
        /// <returns></returns>
        public ResultModel change_position(string change_type, string type_id)
        {
            return CoreStartDo.ResultAction<ResultModel>(result =>
            {
                knowledge_type should_change_item = getknowledge_list.Where(s => s.type_id == type_id).SingleOrDefault();
                if (should_change_item == null)
                {
                    result.code = 1;
                    result.msg = "选定类型不存在";
                    return result;
                }
                if (!should_change_item.sort.HasValue)
                {
                    should_change_item.sort = 1;
                }
                knowledge_type change_item = null;
                switch (change_type)
                {
                    case "up":
                        //尝试获取前面的数据
                        change_item = getknowledge_list.Where(s => s.parent_id == should_change_item.parent_id && s.sort < should_change_item.sort).OrderByDescending(s => s.sort).Take(1).FirstOrDefault();
                        if (change_item == null)
                        {
                            result.code = 1;
                            result.msg = "已经是第一个";
                            return result;
                        }
                        break;
                    case "down":
                        //尝试获取后面的数据
                        change_item = getknowledge_list.Where(s => s.parent_id == should_change_item.parent_id && s.sort > should_change_item.sort).OrderBy(s => s.sort).Take(1).FirstOrDefault();
                        if (change_item == null)
                        {
                            result.code = 1;
                            result.msg = "已经是最后一个";
                            return result;
                        }
                        break;
                    default:
                        result.code = 1;
                        result.msg = "弄啥嘞？";
                        return result;
                }
                //互换两个ID的编号数据
                List<object> updateobj = new List<object>();
                updateobj.Add(new { type_id = should_change_item.type_id, sort = change_item.sort });
                updateobj.Add(new { type_id = change_item.type_id, sort = should_change_item.sort });
                int rows = _tool.di_db.do_Execute("update knowledge_type set sort=@sort where type_id=@type_id", updateobj);
                if (rows > 0)
                {
                    result.code = 0;
                    result.msg = "success";
                    refknowledge_list();
                }
                else
                {
                    result.code = 1;
                    result.msg = "操作失败" + rows;
                }
                return result;
            });
        }
        #endregion 
        /// <summary>
        /// 保存知识库文章
        /// </summary>
        /// <returns></returns>
        public ResultObjModel save_knowledge(knowledge_base Params)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(Params.title))
                {
                    result.code = 1;
                    result.msg = "知识库标题不能为空";
                    return result;
                }
                //if (string.IsNullOrWhiteSpace(Params.content))
                //{
                //    result.code = 1;
                //    result.msg = "知识库内容不能为空";
                //    return result;
                //}
                if (!string.IsNullOrWhiteSpace(Params.type_a))
                {
                    Params.type_a_name = !getknowledge_list.Where(s => s.type_id == Params.type_a).Any() ? "" : getknowledge_list.Where(s => s.type_id == Params.type_a).FirstOrDefault().type_name;
                }
                if (!string.IsNullOrWhiteSpace(Params.type_b))
                {
                    Params.type_b_name = !getknowledge_list.Where(s => s.type_id == Params.type_b).Any() ? "" : getknowledge_list.Where(s => s.type_id == Params.type_b).FirstOrDefault().type_name;
                }
                if (!string.IsNullOrWhiteSpace(Params.type_c))
                {
                    Params.type_c_name = !getknowledge_list.Where(s => s.type_id == Params.type_c).Any() ? "" : getknowledge_list.Where(s => s.type_id == Params.type_c).FirstOrDefault().type_name;
                }
                string strText = "";
                if (!string.IsNullOrWhiteSpace(Params.content))
                {
                    strText = HttpUtility.HtmlDecode(Params.content);
                    strText = Regex.Replace(strText, @"<[\s\S]*?>", "", RegexOptions.IgnoreCase);
                }
                if (string.IsNullOrWhiteSpace(Params.Id))
                {
                    //直接添加数据
                    Params.add_time = DateTime.Now;
                    Params.add_user = _tool.di_user.USER.uid;
                    Params.Id = _tool.di_getid.IGet_SnowFlake_Id;
                    Params.isdelete = false;
                    Params.last_edit_time = DateTime.Now;
                    Params.content_des = $"{ Params.type_a_name},{Params.type_b_name},{Params.type_c_name }...{strText}";
                    Params.state = 0;//默认放到草稿箱
                    Params.is_share = false;
                    Params.is_long = true;
                    object addresult = _es_service.Add_Item(Params);
                    result.code = 0;
                    result.msg = "保存成功";
                    //result.data = addresult;
                }
                else
                {
                    knowledge_base update_doc = _es_service.get_es_model(Params.Id);
                    if (update_doc == null)
                    {
                        result.code = 1;
                        result.msg = "修改数据不存在";
                        return result;
                    }
                    if (update_doc.state == 1)
                    {
                        result.code = 1;
                        result.msg = "当前文档已发布,不允许修改";
                        return result;
                    }
                    update_doc.author = Params.author;
                    update_doc.content = Params.content;
                    update_doc.content_des = $"{ Params.type_a_name},{Params.type_b_name},{Params.type_c_name }...{strText}";
                    update_doc.title = Params.title;
                    update_doc.type_a = Params.type_a;
                    update_doc.type_b = Params.type_b;
                    update_doc.type_c = Params.type_c;
                    update_doc.type_a_name = Params.type_a_name;
                    update_doc.type_b_name = Params.type_b_name;
                    update_doc.type_c_name = Params.type_c_name;
                    update_doc.state = Params.state;
                    update_doc.show_time = Params.show_time;
                    update_doc.last_edit_time = DateTime.Now;
                    update_doc.is_rk_private = Params.is_rk_private;
                    update_doc.hit = Params.hit;
                    object addresult = _es_service.Update_row(update_doc);
                    result.code = 0;
                    result.msg = "保存成功";
                    //result.data = addresult;
                }
                return result;
            });
        }
        /// <summary>
        /// 查询搜索
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultObjModel knowledge_search(knowledge_search query)
        {
            return CoreStartDo.ResultAction(result =>
            {
                var mod = _es_service.Es_query(query, ""); //_tool.di_user.USER.uid
                result.code = 0;
                result.msg = "success";
                result.data = mod;
                return result;
            });
        }

        /// <summary>
        /// 查询搜索
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultObjModel knowledge_search_to_public(knowledge_search query)
        {
            return CoreStartDo.ResultAction(result =>
            {
                query.state = 1; //显示所有已发布的
                var mod = _es_service.Es_query(query, "");
                result.code = 0;
                result.msg = "success";
                result.data = mod;
                return result;
            });
        }
        /// <summary>
        /// 根据ID获取知识库内文章信息
        /// </summary>
        /// <returns></returns>
        public ResultObjModel get_knowledge(string id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    result.code = 1;
                    result.msg = "关键参数未入参";
                    return result;
                }
                var mod = _es_service.get_es_model(id);
                result.code = 0;
                result.msg = "success";
                result.data = mod;
                return result;
            });
        } 
        /// <summary>
        /// 删除文档
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultObjModel del_knowledge(string id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    result.code = 1;
                    result.msg = "关键参数未入参";
                    return result;
                }
                var esmod = _es_service.get_es_model(id);
                if (esmod == null)
                {
                    result.code = 1;
                    result.msg = "待删除文章不存在";
                    return result;
                }
                var mod = _es_service.Es_delete(id);
                result.code = 0;
                result.msg = "success";
                //result.data = mod;
                return result;
            });
        }
        /// <summary>
        /// 变更知识库文档状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ResultObjModel change_knowledge_state(string id, int? state,DateTime? showtime =null)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    result.code = 1;
                    result.msg = "关键参数未入参";
                    return result;
                }
                if (!state.HasValue)
                {
                    result.code = 1;
                    result.msg = "待修改状态未知";
                    return result;
                }
                var mod = _es_service.get_es_model(id);
                if (mod == null)
                {
                    result.code = 1;
                    result.msg = "文档不存在";
                    return result;
                }
                mod.state = state.Value;
                if (state.Value == 1)
                {
                    if (!showtime.HasValue)
                    {
                        mod.show_time = DateTime.Now;
                    }
                    else
                    {
                        mod.show_time = showtime.Value;
                    }
                }
                var es_result = _es_service.Update_row(mod);
                result.code = 0;
                result.msg = "修改成功";
                //result.data = es_result;
                return result;
            });
        }

        /// <summary>
        /// 分享知识库
        /// </summary>
        /// <returns></returns>
        public ResultObjModel start_share(string id, bool? is_long, share_params? set_params)
        { 
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    result.code = 1;
                    result.msg = "文档ID不能为空";
                    return result;
                }
                if (!is_long.HasValue)
                {
                    result.code = 1;
                    result.msg = "必须设置是否长期";
                    return result;
                }
                if (!is_long.Value && !set_params.HasValue)
                { 
                    result.code = 1;
                    result.msg = "非长期分享必须选择分享时间";
                    return result;
                }
                var mod = _es_service.get_es_model(id); 
                if (mod == null)
                {
                    result.code = 1;
                    result.msg = "文档不存在";
                    return result;
                }
                if (mod.state == 0)
                {
                    result.code = 1;
                    result.msg = "草稿箱内文档不允许分享";
                    return result;
                }
                mod.is_share = true;
                mod.is_long = is_long.Value;
                mod.set_params = is_long.Value ? 0 : (int)set_params.Value;
                if (set_params.HasValue)
                {
                    switch (set_params.Value)
                    {
                        case share_params.四小时:
                            mod.share_end_time = DateTime.Now.AddHours(4);
                            break;
                        case share_params.一天:
                            mod.share_end_time = DateTime.Now.AddDays(1);
                            break;
                        case share_params.三天:
                            mod.share_end_time = DateTime.Now.AddDays(3);
                            break;
                        case share_params.一周:
                            mod.share_end_time = DateTime.Now.AddDays(7);
                            break;
                        case share_params.两周:
                            mod.share_end_time = DateTime.Now.AddDays(14);
                            break;
                        case share_params.一个月:
                            mod.share_end_time = DateTime.Now.AddMonths(1);
                            break;
                        case share_params.三个月:
                            mod.share_end_time = DateTime.Now.AddMonths(3);
                            break;
                    }
                } 
                var es_result = _es_service.Update_row(mod);
                result.code = 0;
                result.msg = "设置成功";
                //result.data = es_result;
                return result;
            });
        }

        /// <summary>
        /// 取消分享
        /// </summary>
        /// <returns></returns>
        public ResultObjModel cancel_share(string id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    result.code = 1;
                    result.msg = "文档ID不能为空";
                    return result;
                } 
                var mod = _es_service.get_es_model(id); 
                if (mod == null)
                {
                    result.code = 1;
                    result.msg = "文档不存在";
                    return result;
                } 
                mod.is_share = false; 
                var es_result = _es_service.Update_row(mod);
                result.code = 0;
                result.msg = "设置成功";
                //result.data = es_result;
                return result;
            });
        }


        /// <summary>
        /// 根据ID获取知识库内文章信息
        /// </summary>
        /// <returns></returns>
        public ResultObjModel get_knowledge_for_share(string id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    result.code = 1;
                    result.msg = "关键参数未入参";
                    return result;
                }
                var mod = _es_service.get_es_model(id);
                if (mod.state == 0)
                {
                    result.code = 1;
                    result.msg = "信息不存在 Error:0";
                    return result;
                }
                if (!mod.is_share)
                {
                    result.code = 1;
                    result.msg = "信息不存在 Error:1";
                    return result;
                } 
                if (mod.is_share && !mod.is_long && mod.share_end_time < DateTime.Now)
                {
                    result.code = 1;
                    result.msg = "信息已过期";
                    return result;
                }
                result.code = 0;
                result.msg = "success";
                result.data = mod;
                return result;
            });
        }


        #region  看板数据 
        /// <summary>
        /// 获取看板首页数据
        /// </summary>
        /// <returns></returns>
        public ResultObjModel get_kanban_index(string type_id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                var sale_type = _tool.di_db.GetList<kanban_index_result>("select * from knowledge_type where parent_id=@parent_id order by sort", new { parent_id = type_id });
                if (sale_type.Any())
                {
                    long total_count = 0;
                    //获取当前已读文章数量
                    long total_read_count = _es_service.Es_query_isread_count(new Entity.knowledge_search()
                    {
                        state = 1,
                        type_a = type_id
                    },
                    _tool.di_user.USER.uid);
                    //获取获取可见的新文章库数据数量
                    long total_new_count = _es_service.Es_query_count(new Entity.knowledge_search()
                    {
                        state = 1,
                        type_a = type_id,
                        start_date = DateTime.Now.AddMonths(-1).ToString()
                    }, "");
                    foreach (var item in sale_type)
                    {
                        var query_params = new Entity.knowledge_search()
                        {
                            page = 1,
                            pagesize = 5,
                            state = 1, //查询在知识库的
                            type_a = type_id,
                            type_b = item.type_id
                        };
                        long total_type_count = 0;
                        var query_reuslt = _es_service.Es_query_for_kanban(query_params, _tool.di_user.USER.uid,ref total_type_count, sd =>
                        {
                            //排序 
                            sd.Descending(d => d.show_time);
                            return sd;
                        });
                        item.list = query_reuslt;
                        total_count += total_type_count; 
                    }

                    result.code = 0;
                    result.msg = "success";
                    result.data = new
                    {
                        total_count,
                        total_new_count,
                        total_read_count,
                        total_no_read_count = total_count - total_read_count,
                        type_list = sale_type
                    };
                }
                else {
                    result.code = 1;
                    result.msg = "分类数据不存在";
                }
                return result;
            });
        }
        /// <summary>
        /// 标记已读
        /// </summary>
        /// <returns></returns>
        public ResultObjModel read_knowledge(string uid,string id) {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(uid))
                {
                    result.code = 1;
                    result.msg = "unkonw uid";
                    return result;
                }
                knowledge_base update_doc = _es_service.get_es_model(id);
                if (update_doc == null)
                {
                    result.code = 1;
                    result.msg = "data is undefined";
                    return result;
                }
                if (update_doc.read_list == null)
                {
                    update_doc.read_list = new List<read_item>() { new read_item() { read_id = uid } }; 
                }
                if (!update_doc.read_list.Where(s => s.read_id == uid).Any())
                {
                    update_doc.read_list.Add(new read_item() { read_id = uid });
                }
                var postresult=  _es_service.Update_row(update_doc);
                result.code = 0;
                result.msg = "success";
                result.data = postresult;
                return result;
            });
        }
        /// <summary>
        ///  获取指定类型下文章列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultObjModel get_kanban_pagelist(knowledge_search query)
        {
            return CoreStartDo.ResultAction(result =>
            {
                query.state = 1; 
                if (string.IsNullOrWhiteSpace(query.type_a))
                {
                    result.code = 1;
                    result.msg = "必须告知组织";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(query.type_b))
                {
                    result.code = 1;
                    result.msg = "必须告知类型";
                    return result;
                } 
                long total_count = 0;
                //获取当前已读文章数量
                long total_read_count = _es_service.Es_query_isread_count(query, _tool.di_user.USER.uid);
                query.start_date = DateTime.Now.AddMonths(-1).ToString();
                //获取获取可见的新文章库数据数量
                long total_new_count = _es_service.Es_query_count(query, ""); 
                long total_type_count = 0;
                var query_reuslt = _es_service.Es_query_for_kanban(query, _tool.di_user.USER.uid, ref total_type_count, sd =>
                {
                    //排序 
                    sd.Descending(d => d.show_time);
                    return sd;
                });
                result.code = 0;
                result.msg = "success";
                result.data = new
                {
                    total_count,
                    total_new_count,
                    total_read_count,
                    total_no_read_count = total_count - total_read_count,
                    type_list = query_reuslt
                };
                return result;
            });
        }


        /// <summary>
        ///  获取指定类型下文章列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultObjModel search_kanben_pagelist(knowledge_search query)
        {
            return CoreStartDo.ResultAction(result =>
            {
                query.state = 1;
                if (string.IsNullOrWhiteSpace(query.type_a))
                {
                    result.code = 1;
                    result.msg = "必须告知组织";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(query.search_title))
                {
                    result.code = 1;
                    result.msg = "搜索关键字不能为空";
                    return result;
                }
                long total_type_count = 0;
                var query_reuslt = _es_service.Es_query_for_kanban(query, _tool.di_user.USER.uid, ref total_type_count);
                result.code = 0;
                result.msg = "success";
                result.data = query_reuslt;
                return result;
            });
        }
        #endregion
    }
}
